package me.firstapp.repository.weixin.product.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Repository;

import me.firstapp.common.utils.Page;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.weixin.product.RebateGrid;
import me.firstapp.repository.base.impl.EntityRepositoryImpl;
import me.firstapp.repository.weixin.product.RebateGridRepository;

@Repository
public class RebateGridRepositoryImpl extends EntityRepositoryImpl<RebateGrid> implements RebateGridRepository {

	@Override
	protected Class<RebateGrid> getPersistentClass() {
		return RebateGrid.class;
	}

	@Override
	public List<RebateGrid> findByProductId(Long productId) {
		StringBuilder sql = new StringBuilder(" FROM RebateGrid bean WHERE 1=1 ");
		Map<String, Object> parameters = new HashMap<>();

		sql.append(" AND bean.productId = :productId ");
		parameters.put("productId", productId);

		return super.query(RebateGrid.class, sql.toString(), parameters);
	}

	@Override
	public Page<RebateGrid> findRebateGridPage(Long productId, Integer pageNo, Integer pageSize,
			Map<String, Object> searchParams, String sortParam, String sortType) {
		StringBuilder sql = new StringBuilder(" FROM RebateGrid bean WHERE 1=1 ");
		Map<String, Object> parameters = new HashMap<String, Object>();

		if (searchParams != null) {
			Set<String> keys = searchParams.keySet();
			for (String key : keys) {
				Object value = searchParams.get(key);
				if (value != null) {
					sql.append(" AND bean." + key + " LIKE :" + key + " ");
					parameters.put(key, "%" + value + "%");
				}
			}
		}

		sql.append(" AND bean.productId =:productId ");
		parameters.put("productId", productId);

		if (StrUtils.isNotNULL(sortParam) && StrUtils.isNotNULL(sortType)) {
			sql.append(" ORDER BY " + sortParam + " " + sortType);
		}

		return super.queryForPage(RebateGrid.class, sql.toString(), parameters, pageNo, pageSize);
	}

}
